package com.link.base.tencent.youtu.controller;

import com.alibaba.fastjson.JSONObject;
import com.link.core.cllog.LCLogger;
import com.link.base.tencent.youtu.model.Face;
import com.link.base.tencent.youtu.model.NormalObj;
import com.link.base.tencent.youtu.model.Store;
import com.link.base.tencent.youtu.model.YoutuImg;
import com.link.base.tencent.youtu.service.YoutuService;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.service.ServiceException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 优图人脸识别-可外部直接访问
 *
 * @author ouyangzhenqiang
 * @date 2018/12/29
 */
@Controller
@RequestMapping("link/face/external")
public class YoutuExternalController {
    /**
     * 魔法值
     */
    private static final String yStr = "Y";
    private static final String nStr = "N";
    @Resource
    public YoutuService youtuService;

    /**
     * 重置优图数据库，清空优图相关表数据、清空腾讯上项目下的所有数据，包括接待记录
     *
     * @author ouyangzhenqiang
     * @date 2018/12/29
     */
    @RequestMapping(value = "/resetYoutu", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> resetYoutu(HttpSession session, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();
        LCLogger.info().withMessageKey("resetYoutu").withMessage("人脸识别 => 重置优图数据库...").flush();

        try {
            // 使用预置参数-密钥
            youtuService.safeCheck(request.getParameter("token"));
            // 需要重置的门店
            Store tempStore = youtuService.storeCheck(Long.parseLong(request.getParameter("storeId")));
            // 是否保留历史接待数据
            String retainReception = request.getParameter("retainReception");
            youtuService.resetYoutu(retainReception, tempStore);

            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 个体管理入口 - 接收图片资源，进行人脸检测分析、人脸检索、个体创建
     * 当人脸信息接入时，需要提供对应的门店Id信息，以用于识别挂载到哪个门店分组下
     *
     * @author ouyangzhenqiang
     * @date 2018/12/29
     * @param record
     */
    @RequestMapping(value = "/personcome", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> personcome(@JsonParam YoutuImg record, HttpSession session, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();
        LCLogger.info().withMessageKey("personcome").withMessage("人脸识别 => 人脸识别数据接入...").flush();
        try {
            // 使用预置参数-密钥
            youtuService.safeCheck(record.getParam2());
            // 门店
            Store tempStore = youtuService.storeCheck(Long.parseLong(record.getParam1()));
            // 入口
            youtuService.personcome(record, tempStore);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 人脸对比
     *
     * @author ouyangzhenqiang
     * @date 2018/12/29
     */
    @RequestMapping(value = "/faceCompare", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> faceCompare(@JsonParam YoutuImg record, HttpSession session, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();
        LCLogger.info().withMessageKey("faceCompare").withMessage("Youtu-人脸对比...").flush();
        try {
            // 使用预置参数-密钥
            youtuService.safeCheck(record.getParam2());
            // 门店
            Store tempStore = youtuService.storeCheck(Long.parseLong(record.getParam1()));
            // 图片处理
            String isCode = youtuService.codeCheck(record);
            String faceUrlA = "";
            String faceUrlB = "";
            if (yStr.equals(isCode)) {
                faceUrlA = youtuService.getHttpUrlByCode(record.getImgStr());
                faceUrlB = youtuService.getHttpUrlByCode(record.getImgStr1());
            } else if (nStr.equals(isCode)) {
                String urlA = record.getUrl();
                String urlB = record.getUrl1();
                if (StringUtils.isBlank(urlA) || StringUtils.isBlank(urlB)) {
                    throw new ServiceException("YOUTU-003");
                }
                faceUrlA = urlA;
                faceUrlB = urlB;
            }

            /* 调用腾讯人脸对比接口 */
            NormalObj normalObj = youtuService.faceCompare(faceUrlA, faceUrlB, tempStore.getCorpId().toString());

            result.put("success", true);
            result.put("result", normalObj);
            result.put("faceUrlA", faceUrlA);
            result.put("faceUrlB", faceUrlB);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 人脸检测与分析
     *
     * @author ouyangzhenqiang
     * @date 2018/12/29
     */
    @RequestMapping(value = "/faceDetect", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> faceDetect(@JsonParam YoutuImg record, HttpSession session, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();
        LCLogger.info().withMessageKey("faceDetect").withMessage("Youtu-人脸检测与分析...").flush();
        try {
            // 使用预置参数-密钥
            youtuService.safeCheck(record.getParam2());
            // 门店
            Store tempStore = youtuService.storeCheck(Long.parseLong(record.getParam1()));
            // 图片处理
            String isCode = youtuService.codeCheck(record);
            String faceUrl = "";
            if (yStr.equals(isCode)) {
                faceUrl = youtuService.getHttpUrlByCode(record.getImgStr());
            } else if (nStr.equals(isCode)) {
                String url = record.getUrl();
                if (StringUtils.isBlank(url)) {
                    throw new ServiceException("YOUTU-003");
                }
                faceUrl = url;
            }

            /* 调用腾讯人脸检测与分析接口 */
            String imageInfo = youtuService.faceDetect(faceUrl, tempStore.getCorpId().toString());
            JSONObject faceInfoObj = JSONObject.parseObject(imageInfo);
            JSONObject faceData = faceInfoObj.getJSONObject("data");
            JSONObject faceObj = faceData.getJSONArray("face").getJSONObject(0);
            Face face = new Face();
            face.setAge(faceObj.getString("age"));
            face.setGender(faceObj.getString("gender"));
            face.setGlass(faceObj.getString("glass"));
            face.setExpression(faceObj.getString("expression"));
            face.setMask(faceObj.getString("mask"));
            face.setHat(faceObj.getString("hat"));
            face.setBeauty(faceObj.getString("beauty"));

            result.put("success", true);
            result.put("result", face);
            result.put("imageUrl", faceUrl);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 人脸验证
     *
     * @author ouyangzhenqiang
     * @date 2018/12/29
     */
    @RequestMapping(value = "/faceVerify", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> faceVerify(@JsonParam YoutuImg record, HttpSession session, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();
        LCLogger.info().withMessageKey("faceVerify").withMessage("Youtu-人脸验证...").flush();
        try {
            // 使用预置参数-密钥
            youtuService.safeCheck(record.getParam2());
            // 门店
            Store tempStore = youtuService.storeCheck(Long.parseLong(record.getParam1()));
            String personId = record.getParam3();
            if (StringUtils.isBlank(personId)) {
                throw new ServiceException("YOUTU-004");
            }
            // 图片处理
            String isCode = youtuService.codeCheck(record);
            String faceUrl = "";
            if (yStr.equals(isCode)) {
                faceUrl = youtuService.getHttpUrlByCode(record.getImgStr());
            } else if (nStr.equals(isCode)) {
                String url = record.getUrl();
                if (StringUtils.isBlank(url)) {
                    throw new ServiceException("YOUTU-003");
                }
                faceUrl = url;
            }

            /* 调用腾讯人脸验证接口 */
            NormalObj normalObj = youtuService.faceVerify(personId, faceUrl, tempStore.getCorpId().toString());

            result.put("success", true);
            result.put("result", normalObj);
            result.put("imageUrl", faceUrl);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

}
